Aug 25, 2023
Authentication System: Django provides a built-in authentication system that allows you to manage user authentication and authorization. It includes user models, views, forms, and templates for handling authentication-related tasks.
User Model: The User model in django.contrib.auth.models represents user accounts. It includes fields like username, email, and password for user authentication.
Login: Login is the process of verifying a user’s identity using their credentials (usually a username and password). Django provides a LoginView for handling user login. It involves checking the provided credentials against the stored credentials in the database.
Logout: Logout is the process of ending a user’s session. Django provides a LogoutView for handling user logout. It involves clearing the session data and redirecting the user to a specified URL.
Signup/Register: Signup or registration is the process of allowing users to create new accounts. Django doesn’t provide a built-in view for signup, but you can use the UserCreationForm from django.contrib.auth.forms to create a registration form. Upon successful registration, users are typically logged in automatically.
Sessions and Cookies: Django uses sessions and cookies to manage user authentication. A session is a way to store user-related data across multiple requests. Cookies are used to store session IDs on the user’s browser.
Middleware: Django’s authentication system relies on middleware to handle user authentication. The AuthenticationMiddleware authenticates users based on the session and populates the request.user object with user information.
Templates and Views: Django provides built-in templates and views for authentication, including login and logout. You can customize these templates and views to match your project’s design and requirements.
URLs and URL Patterns: URLs are used to route requests to the appropriate views. You need to define URL patterns for login, logout, and other authentication-related actions in your urls.py file.
Signals: Django’s authentication system uses signals to perform actions when specific events occur. For example, you can use signals to perform tasks after a user logs in or logs out.
Authentication Decorators: Decorators like @login_required can be applied to views to restrict access to authenticated users. Users who aren’t logged in are redirected to the login page.
Customization: You can customize the authentication system to fit your project’s requirements. This includes using custom user models, creating custom authentication backends, and extending built-in views and forms.
# Create a new Django project
django-admin startproject AuthDemoProject
# Change into the project directory
cd AuthDemoProject
# Create a new app named "accounts"
python manage.py startapp accountsIn AuthDemoProject/urls.py, include the app’s URLs:
In accounts/views.py, you don’t need to create custom login and logout views because Django provides built-in views for authentication:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render, redirect
from django.contrib import messages
def dashboard(request):
return render(request, 'accounts/dashboard.html')
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, 'Login successful.')
return redirect('dashboard')
else:
messages.error(request, 'Invalid login credentials.')
return render(request, 'accounts/login.html')
def custom_logout(request):
logout(request)
return render(request, 'accounts/logout.html')
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, 'Signup successful. Welcome!')
return redirect('dashboard')
else:
form = UserCreationForm()
return render(request, 'accounts/signup.html', {'form': form})Inside the accounts app directory, create a templates/accounts directory. In this directory, create the following template.
accounts/signup.html -
accounts/dashboard.html:
<!DOCTYPE html>
<html>
<head>
<title>User Dashboard</title>
</head>
<body>
<h1>User Dashboard</h1>
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<p>You are not logged in.</p>
<a href="{% url 'login' %}">Login</a>
{% endif %}
</body>
</html>accounts/login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username" required><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>accounts/logout.html:
In the accounts app directory, create a urls.py file:
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
path('logout/', views.custom_logout, name='logout'),
path('dashboard/', views.dashboard, name='dashboard'),
path('signup/', views.signup, name='signup'), # New URL pattern
]Run the development server:
Step 7: Access the Pages
Visit the following URLs in your browser:
Manish Patel